import React, { PureComponent } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';
import * as Utils from '@/utils/utils';
import AccountJS from '@/utils/account';

import RenderAuthorized from '@/components/Authorized';

import {
  Badge,
  Row,
  Col,
  Card,
  Table,
  Form,
  Button,
  Input,
  Icon,
  Select,
  DatePicker,
  Dropdown,
  Radio,
  Tooltip,
  InputNumber,
  Menu,
} from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ReceiveForm from '@/components/ReceiveForm';

import styles from './styles.less';

const { Option } = Select;
const { Item: FormItem } = Form;
const { Item: MenuItem } = Menu;
const { RangePicker } = DatePicker;
const { Button: RadioButton, Group: RadioGroup } = Radio;

const ModelName = 'receivable';

@connect(({ user, receivable, loading, faPiaoState, tiDanState, currency }) => ({
  loading: loading.models[ModelName],
  model: receivable,
  fps: faPiaoState.list,
  tds: tiDanState.list,
  curs: currency.list,
  cUser: user.currentUser,
}))
@Form.create()
class Comp extends PureComponent {
  invType = 0;

  state = {
    recFormVisible: false,
    currentInv: {},
    isDirty: false,
  };

  componentDidMount() {
    const { match } = this.props;
    const path = match.url.split('/').pop();
    this.invType = path === 'Payable' ? 2 : 1;
    this.doQuery();
  }

  doQuery(cond) {
    const { dispatch, model, cUser, } = this.props;
    let payload = {
      ...model.qc,
      invType: this.invType,
    };
    if (cond) {
      payload = {
        ...payload,
        ...cond,
      };
    }

    dispatch({
      type: `${ModelName}/get`,
      payload: payload,
    });
  }

  handlePageChange = (number, size) => {
    const cond = {
      pageSize: size,
      pageNumber: number,
    };
    this.doQuery(cond);
  };

  handleRelationerDetail = rel => {
    // const { dispatch } = this.props;
    // router.push('bill/' + bill.objectNumber);
    console.log('RELATIONER DETAIL', rel);
  };

  handleLockClick = record => {
    const recItem = {
      invoiceId: record.invoiceId,
      currencyId: record.currencyId,
      currecyName: record.currencyName,
      amount: record.amount,
      receive: record.receive,
      isRecLock: record.isRecLock,
      invoiceType: record.invoiceType,
      memo: record.memo
    };
    this.setState({
      // 直接显示，核销或解锁都在对话框里面做。
      recFormVisible: true,
      currentInv: recItem,
    });
  };

  handleRecFormSubmit = () => {
    const { dispatch } = this.props;
    const { form } = this.recForm.props;
    const { currentInv } = this.state;

    form.validateFields((err, values) => {
      if (err) {
        return;
      }

      const payload = {
        invoiceId: currentInv.invoiceId,
        currencyId: currentInv.currencyId,
        receive: values.receive,
        isRecLock: values.isRecLock ? 1 : 0,
        lockDate: values.lockDate ? Utils.getChineseDate(values.lockDate) : null,
        memo: values.memo
      };

      dispatch({
        type: `${ModelName}/receipt`,
        payload: payload,
        callback: resp => {
          if (resp) {
            this.setState({ recFormVisible: false });
            this.doQuery();
          }
        },
      });
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const payload = {
        ...fieldsValue,
        recLockStart:
          fieldsValue.recLockDate && Array.isArray(fieldsValue.recLockDate)
            ? Utils.getChineseDate(fieldsValue.recLockDate[0])
            : null,
        recLockEnd:
          fieldsValue.recLockDate && Array.isArray(fieldsValue.recLockDate)
            ? Utils.getChineseDate(fieldsValue.recLockDate[1])
            : null,
      };
      delete payload.recLockDate;
      this.doQuery(payload);
    });
  };

  handleFormReset = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.resetFields();
    dispatch({
      type: `${ModelName}/reSetQC`,
      payload: {
        invType: this.invType
      }
    });
  };

  handleInvFPSChanged = (e, record) => {
    const { dispatch } = this.props;
    const pd = {
      invId: record.invoiceId,
      state: e.key,
    };
    dispatch({
      type: `inv/changeInvFPS`,
      payload: pd,
      callback: () => {
        this.doQuery();
      },
    });
  };

  handleInvTDSChanged = (e, record) => {
    const { dispatch } = this.props;
    const pd = {
      invId: record.invoiceId,
      state: e.key,
    };
    dispatch({
      type: `inv/changeInvTDS`,
      payload: pd,
      callback: () => {
        this.doQuery();
      },
    });
  };

  handleMBLStateChanged = (e, record) => {
    console.log("MBL STATE CHANGED.", e.key, record);
    const { dispatch } = this.props;
    const pd = {
      billId: record.billId,
      stateId: e.key,
    };
    dispatch({
      type: `receivable/changeTiDanState`,
      payload: pd,
      callback: () => {
        this.doQuery();
      },
    });
  };

  queryForm = () => {
    const {
      form: { getFieldDecorator },
      model,
    } = this.props;

    const { fps, tds, curs } = this.props;
    const { qc } = model;

    const colSpanLayout = {
      xs: 24,
      md: 12,
      lg: 6,
    };

    const formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
        lg: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 },
        lg: { span: 17 },
      },
    };

    return (
      <Form onSubmit={this.handleSearch}>
        <Row gutter={1} className={styles.dataRow}>
          <Col {...colSpanLayout}>
            <FormItem label="关键字" {...formLayout}>
              {getFieldDecorator('keyword', {
                initialValue: qc.keyword,
              })(<Input placeholder="单位名称、单号" onChange={() => {
                // this.setState({ isDirty: true });
                console.log("dirty！！");
              }} />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="金额" {...formLayout}>
              {getFieldDecorator('amount')(<InputNumber style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="发票" {...formLayout}>
              {getFieldDecorator('faPiaoStateId')(
                <Select placeholder="请选择">
                  {fps.map(p => (
                    <Option value={p.id} key={p.id}>
                      {p.objectName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="分单提单" {...formLayout}>
              {getFieldDecorator('tiDanStateId', {
                initialValue: qc.tiDanStateId,
              })(
                <Select placeholder="请选择">
                  {tds.map(p => (
                    <Option value={p.id} key={p.id}>
                      {p.objectName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="主单提单" {...formLayout}>
              {getFieldDecorator('mblTiDanStateId', {
                initialValue: qc.mblTiDanStateId,
              })(
                <Select placeholder="请选择">
                  {tds.map(p => (
                    <Option value={p.id} key={p.id}>
                      {p.objectName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="整单核销" {...formLayout}>
              {getFieldDecorator('isBillLock', {
                initialValue: qc.isBillLock,
              })(
                <Select placeholder="请选择">
                  <Option value={-1}>全部</Option>
                  <Option value={0}>未核销</Option>
                  <Option value={1}>已核销</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="单项核销" {...formLayout}>
              {getFieldDecorator('isRecLock', {
                initialValue: qc.isRecLock,
              })(
                <Select placeholder="请选择">
                  <Option value={-1}>全部</Option>
                  <Option value={0}>未核销</Option>
                  <Option value={1}>已核销</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="核销日期" {...formLayout}>
              {getFieldDecorator('recLockDate', {
                initialValue:
                  qc.reclockDateStart && qc.reclockDateEnd
                    ? [moment(qc.reclockDateStart), moment(qc.reclockDateEnd)]
                    : null,
              })(<RangePicker />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="币种" {...formLayout}>
              {getFieldDecorator('currencyId')(
                <Select placeholder="请选择">
                  {curs.map(p => (
                    <Option value={p.id} key={p.id}>
                      {p.objectName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col>
            <div style={{ float: 'right', marginBottom: '4px', zIndex: '9999' }}>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    const { model, loading, fps, tds, cUser } = this.props;
    const { recFormVisible, currentInv } = this.state;
    const { data } = model;

    const fpsMenu = record => (<Dropdown
      overlay={
        <Menu
          onClick={e => this.handleInvFPSChanged(e, record)}
          selectedKeys={[String(record.faPiaoStateId)]}
        >
          {fps.map(f => (
            <MenuItem key={f.id}>{f.objectName}</MenuItem>
          ))}
        </Menu>
      }
    >
      <span>
        {record.faPiaoState} <Icon type="down" />
      </span>
    </Dropdown >);

    const tdsMenu = record => (<Dropdown
      overlay={
        <Menu
          onClick={e => this.handleInvTDSChanged(e, record)}
          selectedKeys={[String(record.tiDanStateId)]}
        >
          {tds.map(f => (
            <MenuItem key={f.id}>{f.objectName}</MenuItem>
          ))}
        </Menu>
      }
    >
      <span>
        {record.tiDanState} <Icon type="down" />
      </span>
    </Dropdown>);

    const mblMenu = record => (<Dropdown
      overlay={
        <Menu
          onClick={e => this.handleMBLStateChanged(e, record)}
          selectedKeys={[String(record.mblTiDanStateId)]}
        >
          {tds.map(f => (
            <MenuItem key={f.id}>{f.objectName}</MenuItem>
          ))}
        </Menu>
      }
    >
      <span>
        {record.mblTiDanState} <Icon type="down" />
      </span>
    </Dropdown>);

    const footerContent = () => {
      const groupSum = data.tag;
      return groupSum && (
        <div className={styles.relFooter}>
          {groupSum.map(item => (
            <p key={item.currencyName}>
              <span className={styles.currencyName}>{item.currencyName}</span>
              <span className={styles.total}>总额:{AccountJS.format(item.amount, 2)}</span>
              <span className={styles.total}>已结:{AccountJS.format(item.receive, 2)}</span>
              <span className={styles.total}>差额:{AccountJS.format(Math.abs(item.receive - item.amount), 2)}</span>
            </p>
          ))}
        </div>
      );
    };

    const listTable = () => {

      const Authorized = RenderAuthorized(cUser.sys_Role.enCode);

      const action = (record) => {
        return (<Authorized authority={['SysAdmin']}>
          <a
            onClick={() => this.handleLockClick(record)}
            disabled={record.isBillLock === 1}
          >
            {record.isBillLock === 1
              ? '主单锁'
              : record.isLock
                ? '账单锁'
                : record.isRecLock
                  ? '解锁'
                  : '核销'}
          </a>
        </Authorized>
        );
      };

      const columns = [
        {
          title: '#',
          dataIndex: 'ReNo',
          render: (text, record, index) => (
            <span> {index + 1 + (data.currentPage - 1) * data.pageSize} </span>
          ),
        },
        {
          title: '名称',
          dataIndex: 'relationerName',
          render: (text, record) => (
            <div style={{ maxWidth: '200px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              <Tooltip title={text}>{text}</Tooltip>
            </div>
          ),
        },
        {
          title: '单号',
          dataIndex: 'billNumber',
          render: text => <Link to={`/Bill/${text}/INV`}>{text}</Link>,
        },
        {
          title: 'SO号',
          dataIndex: 'so',
        },
        {
          title: this.invType === 2 ? '应付' : '应收',
          dataIndex: 'amount',
          align: 'right',
          render: (text, record) => <span>{AccountJS.format(record.amount, 2)}</span>,
        },
        {
          title: this.invType === 2 ? '实付' : '实收',
          dataIndex: 'receive',
          align: 'right',
          render: (text, record) => <span>{AccountJS.format(record.receive, 2)}</span>,
        },
        {
          title: '币种',
          dataIndex: 'currencyName',
        },
        {
          title: '开船日期',
          dataIndex: 'etd',
          render: (text, record) => <span> {Utils.getChineseDate(record.etd, '')}</span>,
        },
        {
          title: '发票状态',
          dataIndex: 'faPiaoState',
          render: (text, record) => record.isBillLock === 1 ? text : fpsMenu(record),
        },
        {
          title: '业务员',
          dataIndex: 'salerName',
        },
        {
          title: 'HBL单',
          dataIndex: 'tiDanState',
          render: (text, record) => record.isBillLock === 1 ? text : tdsMenu(record),
        },
        {
          title: 'MBL单',
          dataIndex: 'mblTiDanState',
          render: (text, record) => record.isBillLock === 1 ? text : mblMenu(record),
        },
        {
          title: '单项核销',
          dataIndex: 'isRecLock',
          render: (text, record) => (
            <span>
              {record.isRecLock === 1 ? Utils.getChineseDate(record.recLockDate, '已核销') : '未核销'}{' '}
            </span>
          ),
        },
        {
          title: '整单核销',
          dataIndex: 'isBillLock',
          render: (text, record) => (
            <div style={{ textAlign: 'left' }}>
              <span>
                {record.isBillLock === 1 ? Utils.getChineseDate(record.billLockDate, '已核销') : '未核销'}{' '}
              </span>
              <Tooltip style={{ display: record.memo && record.memo.length > 0 ? '' : 'none' }} title={record.memo}>
                <Badge status="error" style={{ display: record.memo && record.memo.length > 0 ? '' : 'none' }} />
              </Tooltip>

            </div>
          ),
        },
        {
          title: '',
          key: 'action',
          render: (text, record) => action(record),
        },
      ];

      const setClassName = (record, index) => {
        return (record.currencyName === 'USD' ? styles.USD : '')
      }

      return (<Table
        rowKey={record => `${record.invoiceId + '-' + record.currencyId}`}
        size="small"
        style={{ marginTop: 12 }}
        loading={loading}
        dataSource={data.dataList}
        rowClassName={setClassName}
        columns={this.invType == 1 ? columns : columns.filter(r => r.dataIndex !== 'tiDanState')}
        pagination={{
          showSizeChanger: true,
          total: data.totalCount,
          pageSize: data.pageSize,
          current: data.currentPage,
          onChange: this.handlePageChange,
          onShowSizeChange: this.handlePageChange,
          showTotal: (total, range) => `共${total}项，当前显示 ${range[0]}-${range[1]}`,
        }}
        footer={() => footerContent()}
      />

      )
    }

    return (
      <PageHeaderWrapper>
        <div className={styles.tableListForm}>{this.queryForm()}</div>

        <Card bordered={false}>
          {listTable()}
        </Card>
        <ReceiveForm
          visible={recFormVisible}
          onOk={this.handleRecFormSubmit}
          receive={currentInv}
          onCancel={() => this.setState({ recFormVisible: false })}
          getInstance={form => (this.recForm = form)}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Comp;
